#include "APlayer.h"

APlayer::APlayer()
{
	setVolume(80);
	setPlaylist(&m_plist);
	m_plist.setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
}

APlayer::~APlayer()
{
	// release all data
	stopNow(false);
	m_plist.clear();
	m_map.clear();
	m_now.clear();
}

void APlayer::stopNow(bool release)
{
	stop();
	if (release && !m_now.empty()) {
		m_plist.removeMedia(m_plist.currentIndex());
		m_map.remove(m_now);
		m_now.clear();
	}
}

bool APlayer::setNow(const std::string& path)
{
	int r = sid(path);
	if (r < 0) return false;
	m_plist.setCurrentIndex(r);
	m_now = path;
	return true;
}

void APlayer::setLoop(bool loop)
{
	m_plist.setPlaybackMode(loop ? QMediaPlaylist::CurrentItemInLoop : QMediaPlaylist::CurrentItemOnce);
}

bool APlayer::add(const std::string& path)
{
	int r = sid(path);
	if (r >= 0) return true;
	QMediaContent con(QUrl::fromLocalFile(QString::fromStdString(path)));
	if (con.isNull())
		return false;
	if (m_plist.addMedia(con)) {
		m_map.insert(path, m_plist.mediaCount() - 1);
		return true;
	}
	return false;
}


int APlayer::sid(const std::string& path)
{
	QMap<std::string, int>::iterator it = m_map.find(path);
	if (it == m_map.end()) {
		return -1;
	}
	return it.value();
}
